package com.bookstore.admin.adminuser.handler;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.bookstore.admin.adminuser.service.IAdminUserService;
import com.bookstore.commons.beans.User;

@Controller
@RequestMapping("/admin/adminUser")
public class AdminUserHandler {

	@Autowired
	private IAdminUserService adminUserService;
	
	@RequestMapping("/loginAdminUser.do")
	public String loginAdminUserHandler(User user,Model model,HttpServletRequest request,HttpServletResponse response,HttpSession session) throws UnsupportedEncodingException {
		User login_user = adminUserService.findAdminUser(user);
		if(login_user != null) {
			session.setAttribute("login_user", login_user);
			if("普通用户".equals(login_user.getRole())) {
				addCookie( login_user, request, response);
				return "/client/index.jsp";
			}else {
				addCookie( login_user, request, response);
				return "/admin/login/home.jsp";
			}
			
			
		}else {
			model.addAttribute("msg", "帐号密码错误！");
			model.addAttribute("user", user);
			
			return "/admin/login/login.jsp";
		}
		
	}
	
	@RequestMapping("/logout.do")
	public String logoutHandler(HttpSession session,HttpServletResponse response) throws UnsupportedEncodingException{
		session.removeAttribute("login_user");
		Cookie login_cookie = new Cookie("login_state",URLEncoder.encode("2", "utf-8") );
		Cookie password_cookie = new Cookie("bookstore_password",URLEncoder.encode(null, "utf-8") );
		response.addCookie(login_cookie);
		response.addCookie(password_cookie);
		return "/admin/login/login.jsp";
	}
	
	
	
	
	
	
	private  void addCookie(User user,HttpServletRequest request,HttpServletResponse response) throws UnsupportedEncodingException{
		Cookie username_cookie = new Cookie("bookstore_username",URLEncoder.encode(user.getUsername(), "utf-8") );
		
		username_cookie.setMaxAge(60*60*24*7);
		username_cookie.setPath(request.getContextPath()+"/");
		response.addCookie(username_cookie);
		
		Cookie login_cookie = new Cookie("login_state",URLEncoder.encode("1", "utf-8") );
		
		login_cookie.setMaxAge(60*60*24*7);
		login_cookie.setPath(request.getContextPath()+"/");
		response.addCookie(login_cookie);
		
	}
}
